<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 第一行 -->
      <el-row :gutter="20">
        <!-- 搜索区 -->
        <el-col :span="10">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>

        <!--添加用户区 -->
        <el-col :span="2">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <!-- 用户列表区 -->
      <el-table :data="userlist" border stripe>
        <el-table-column
          label="序号"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column
          label="姓名"
          prop="username"
          align="center"
        ></el-table-column>
        <el-table-column
          label="邮箱"
          prop="email"
          align="center"
        ></el-table-column>
        <el-table-column
          label="电话"
          prop="mobile"
          align="center"
        ></el-table-column>
        <el-table-column
          label="角色"
          prop="role_name"
          align="center"
        ></el-table-column>
        <el-table-column label="状态" prop="mg_state" align="center">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <!-- 显示这一行的全部数据 -->
            <!--  {{ scope.row }} -->

            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <!--  -->

          <!-- eslint-disable -->
          <template slot-scope="scope">
            <!-- eslint-enable>
            
            <!-- 编辑按钮 -->
            <!-- 提示信息 -->
            <el-tooltip
              effect="dark"
              content="编辑"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="showeditdialog(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 删除按钮 -->
            <!-- 提示信息 -->
            <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="removeUserById(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 分配角色按钮 -->
            <!-- 提示信息 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                circle
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 第三行 -->
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框提示 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addDialogclose"
    >
      <!-- 表单内容主题 -->
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormref"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="userpassword">
          <el-input v-model="addForm.userpassword"></el-input>
        </el-form-item>

        <el-form-item label="号码" prop="usermobile">
          <el-input v-model="addForm.usermobile"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="useremlie">
          <el-input v-model="addForm.useremlie"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="35%"
      @close="setRoleDialogClose"
    >
      <div>
        <p>当前用户：{{ userInfo.username }}</p>
        <p>当前角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  /* 私有的数据 */
  data() {
    /* 验证合法邮箱的方法 */
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };

    //验证手机号的规则;
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };

    return {
      queryInfo: {
        /* 关键字（可以为空） */
        query: "",
        /* 当前页数 */
        pagenum: 1,
        /* 初始每一页有2条数据 */
        pagesize: 2,
      },

      //用户列表
      userlist: [],
      total: 0,
      /* 所有角色数据列表 */
      rolesList: [],

      /* 已选中的角色id */
      selectRoleId: "",

      /*设置对话框为隐藏  */
      dialogVisible: false,
      /* 控制分配角色对话框 */
      setRoleDialogVisible: false,
      addForm: {
        username: "",
        userpassword: "",
        usermobile: "",
        useremlie: "",
      },

      /* 添加表单的验证规则对象 */
      addFormrules: {
        /* 用户名的校验规则 */
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 3,
            max: 8,
            message: "用户名的长度在3-8个字符之间",
            trigger: "blur",
          },
        ],

        /* 密码的校验规则 */
        userpassword: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min: 6,
            max: 12,
            message: "密码的长度在6-15个字符之间",
            trigger: "blur",
          },
        ],

        /* 手机校验 */
        usermobile: [
          {
            required: true,
            message: "请输入号码",
            trigger: "blur",
          },
          {
            validator: checkMobile,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        /* 邮箱校验 */
        useremlie: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            validator: checkEmail,
            message: "请输入正确的邮箱地址",
            trigger: "blur",
          },
        ],
      },
      //控制修改用户框的显示
      editdialogVisible: false,
      /* 需要被分配角色的用户信息 */
      userInfo: {},
      //查询到的用户信息对象
      editForm: {},
      //使用表单验证规则
      editFormRules: {
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            validator: checkEmail,
            message: "请输入正确的邮箱地址",
            trigger: "blur",
          },
        ],

        mobile: [
          {
            required: true,
            message: "请输入号码",
            trigger: "blur",
          },
          {
            validator: checkMobile,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
    };
  },

  /* 生命周期函数 */
  created() {
    this.getUserList();
  },

  /* 一些方法和行为 */
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败");
      }
      (this.userlist = res.data.users),
        (this.total = res.data.total),
        console.log(res);
    },

    /* 监听页面大小变化 */
    handleSizeChange(newSize) {
      /* 在控制台打印当前每页有多少数据 */
      /*  console.log(`每页 ${newSize} 条`); */
      this.queryInfo.pagesize = newSize;
      /* 重新向服务器请求相应的页面 */
      this.getUserList();
    },

    /* 监听页码值改变的事件*/
    handleCurrentChange(newPage) {
      /* 在控制台打印当前页的数据 */
      /* console.log(`当前页: ${newPage}`); */
      this.queryInfo.pagenum = newPage;
      /* 重新向服务器请求相应的页面 */
      this.getUserList();
    },

    /* 将改变的状态值返回到数据库中保存 */
    async userStateChange(userInfo) {
      console.log(userInfo);
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("更新用户状态失败");
      }
      this.$message.success("更新用户状态成功");
    },
    /* 监听添加用户框的关闭重置事件 */
    addDialogclose() {
      this.$refs.addFormref.resetFields();
    },

    //监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },

    //点击确定，添加用户
    async addUser() {
      this.$refs.addFormref.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;
        //发起添加用户数据请求
        const { data: res } = await this.$http.post("users", {
          username: this.addForm.username,
          password: this.addForm.userpassword,
          email: this.addForm.useremlie,
          mobile: this.addForm.usermobile,
        });
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败！");
        }

        //隐藏添加用户对话框
        this.dialogVisible = false;
        //刷新用户列表
        this.getUserList();
        this.$message.success("添加用户成功");
        console.log(res);
      });
    },
    /* 这是编辑的对话用户框 */
    async showeditdialog(id) {
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("查询用户信息失败！");
      }
      this.editForm = res.data;
      this.editdialogVisible = true;
      /* console.log(id); */
    },

    // 修改用户信息并提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        //发起修改用户数据请求
        const { data: res } = await this.$http.put(
          "users/" + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        );

        if (res.meta.status !== 200) {
          return this.$message.error("更新用户信息失败！");
        }
        //关闭对话框
        //刷新数据列表
        //提示更新成功
        this.editdialogVisible = false;
        this.getUserList();
        this.$message.success("更新用户信息成功");
      });
    },
    // 根据id删除对应的用户名
    async removeUserById(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      //console.log(id);
      //如果用户确认删除，则返回值为字符串confirm
      //如果用户取消了删除，则返回值为字符串cancel
      /* console.log(confirmResult); */

      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除操作！");
      } else {
        const { data: res } = await this.$http.delete("users/" + id);
        if (res.meta.status !== 200) {
          return this.$message.error("删除用户失败！");
        } else {
          this.$message.success("删除用户成功！");
          this.getUserList();
        }
      }
    },
    /* 分配角色的对话框 */
    async setRole(userInfo) {
      this.userInfo = userInfo;
      /* 在展示对话框之前，获取所有角色列表 */
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取所有角色失败！");
      }
      this.rolesList = res.data;
      this.setRoleDialogVisible = true;
    },
    /* 更改用户角色 */
    async setRoleInfo() {
      if (!this.selectRoleId) {
        return this.$message.error("请选择分配的角色！");
      } else {
        const { data: res } = await this.$http.put(
          `users/${this.userInfo.id}/role`,
          {
            rid: this.selectRoleId,
          }
        );

        if (res.meta.status !== 200) {
          return this.$message.error("更新角色失败！");
        } else {
          this.$message.success("更新角色成功！");
          this.getUserList();
          this.setRoleDialogVisible = false;
        }
      }
    },
    /* 监听分配角色对话框的关闭事件 */
    setRoleDialogClose() {
      this.selectRoleId = "";
      this.userInfo = {};
    },
  },
};
</script>